package cn.tedu.csmall.product.webapi;

import java.util.Arrays;
import java.util.Scanner;

public class BinarySearch {
    public static void main(String[] args) {
        int[] ary = {1,2,5,8,23,56};
        int result = rank(23,ary);
        System.out.println(result);
    }
    public static int rank(int key, int nums[]) {
        int low = 0;
        int high = nums.length - 1;
        int notFind = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (nums[mid] > key) {
                high = mid - 1;
            } else if (nums[mid] < key) {
                low = mid + 1;
            } else {
                return mid;
            }
        }
        return notFind;
    }

    private static Scanner in;

    public int find(int a[], int b) //a为所要查找的数
    {
        int mid, low = 0, high;
        high = a.length - 1;
        while (low <= high) {
            mid = low + (high - low) / 2;
            if (b < a[mid]) {
                high = mid - 1;
            } else if (b > a[mid]) {
                low = mid + 1;
            } else {
                return mid + 1;
            }
        }
        return 0;
    }

   /* public static void main(String[] args) {
        int a[];
        int t;
        int sum = 0;
        BinarySearch p = new BinarySearch();
        int q2 = 0;
        in = new Scanner(System.in);
        System.out.println("请输⼊数组长度");
        q2 = in.nextInt();
        a = new int[q2];
        System.out.println("请输⼊数组元素");
        for (int i = 0; i < a.length; i++) {
            a[i] = in.nextInt();
        }
        System.out.println("排序后数组为");
        Arrays.sort(a);
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
        System.out.println("请输⼊所要查找的数若未查找到该数则输出-1");
        q2 = in.nextInt();
        for (int i = 0; i < a.length; i++) {
            if (q2 == a[i]) {
                t = 1;
            } else {
                t = 0;
            }
            sum = sum + t;
        }
        if (sum == 0) {
            System.out.println("-1");
        } else {
            System.out.println("所输⼊的数在第" + p.find(a, q2) + "位");
        }
    }
*/
}
